package com.mezz.bones.im.gateway.listener;

import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.im.common.event.MessageSendWithConnectEvent;
import com.mezz.bones.im.common.event.MessageSendWithUserIdEvent;
import com.mezz.bones.im.common.domain.msg.MessageSend2UserConnect;
import com.mezz.bones.im.common.domain.msg.MessageSend2UserId;
import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.common.result.ImResultCode;
import com.mezz.bones.im.gateway.service.IMessageSenderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: zhuang
 * @Date: 2024/12/2 13:56
 * @Description: TODO
 * @Version: 1.0
 **/

@Component
@Slf4j
public class GatewayMessageListener {

    @Resource
    private IMessageSenderService messageSenderService;

    @EventListener
    @Async("imSysMessageActionExecutor")
    public void handleMessageSend(MessageSendWithUserIdEvent event) {

        //消息发送客户端
        String userId = event.getUserId();

        //消息信息
        Object message = event.getData();
        Object traceId = event.getTraceId();
        String actionCode = event.getActionCode();
        ImResultCode resultCode = event.getResultCode();
        log.debug("im gateway send actionCode={},userId={}, message={}", actionCode, userId, JSONObject.toJSONString(message));
        messageSenderService.sendPrivateMessage2UserId(MessageSend2UserId.builder()
                .userId(userId)
                .traceId(traceId.toString())
                .actionCode(actionCode)
                .data(message)
                .resultCode(resultCode)
                .build());
    }

    @EventListener
    @Async("imSysMessageActionExecutor")
    public void handleMessageSend(MessageSendWithConnectEvent event) {

        //消息发送客户端
        ImUserConnectInfo senderUserConnectInfo = event.getSenderUserConnectInfo();

        //消息信息
        Object message = event.getData();
        Object traceId = event.getTraceId();
        String actionCode = event.getActionCode();
        ImResultCode resultCode = event.getResultCode();
        log.debug("im gateway send actionCode={},client={}, message={}", actionCode, JSONObject.toJSONString(senderUserConnectInfo), JSONObject.toJSONString(message));
        messageSenderService.sendPrivateMessage2UserConnect(MessageSend2UserConnect.builder()
                .userConnectInfo(senderUserConnectInfo)
                .traceId(traceId.toString())
                .actionCode(actionCode)
                .data(message)
                .resultCode(resultCode)
                .build());
    }
}
